import qs from 'qs';
import moment from 'moment';
import QichachaProvince from './QichachaProvince.json';

const BASE_URL = 'https://open.api.tianyancha.com/services/open';
const API_RETURN_FIELD = {
  name: {name: '企业名', kintoneFieldType: ['SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT', 'RICH_TEXT']},
  legalPersonName: {name: '法人', kintoneFieldType: ['SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT', 'RICH_TEXT']},
  type: {name: '法人类型', kintoneFieldType: ['SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT', 'RICH_TEXT']},
  regNumber: {name: '注册号', kintoneFieldType: ['SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT', 'RICH_TEXT']},
  regCapital: {name: '注册资本', kintoneFieldType: ['SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT', 'RICH_TEXT']},
  actualCapital: {name: '实收注册资金', kintoneFieldType: ['SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT', 'RICH_TEXT']},
  companyOrgType: {name: '企业类型', kintoneFieldType: ['SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT', 'RICH_TEXT']},
  creditCode: {name: '统一社会信用代码', kintoneFieldType: ['SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT', 'RICH_TEXT']},
  fromTime: {name: '经营开始时间', kintoneFieldType: ['DATETIME']},
  base: {name: '省份简称', kintoneFieldType: ['SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT', 'RICH_TEXT']},
  businessScope: {name: '经营范围', kintoneFieldType: ['SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT', 'RICH_TEXT']},
  regStatus: {name: '企业状态', kintoneFieldType: ['SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT', 'RICH_TEXT']},
  regLocation: {name: '注册地址', kintoneFieldType: ['SINGLE_LINE_TEXT', 'MULTI_LINE_TEXT', 'RICH_TEXT']},
};
const SERVER = {
  NAME: '天眼查',
  ID: 'tyc'
};
export {BASE_URL, API_RETURN_FIELD, SERVER};

export class TianyanchaAPI {
  constructor(pluginId) {
    this.pluginId = pluginId;
  }

  getBaseInfo(data) {
    const requestConfig = this.buildRequestConfig({
      api: 'ic/baseinfo/2.0',
      method: 'GET',
      data
    });
    return this.sendRequest(requestConfig).then(result => {
      return this.parseResult(result);
    });
  }

  buildRequestConfig({api, method, headers = {}, data = {}}) {
    const requestConfig = {
      url: `${BASE_URL}/${api}`,
      method,
      headers,
      data
    };

    switch (method) {
      case 'GET':
      case 'DELETE':
        return {
          ...requestConfig,
          url: `${BASE_URL}/${api}?${qs.stringify(data)}`,
          data: {}
        };
      case 'POST':
      case 'PUT':
      default:
        return requestConfig;
    }
  }

  sendRequest({url, method, headers = {}, data = {}}) {
    return new kintone.Promise((resolve, reject) => {
      kintone.plugin.app.proxy(this.pluginId, url, method, headers, data,
        (body, status) => {
          let response;
          try {
            response = JSON.parse(body);
          } catch (e) {
            response = {};
          }

          if (status === 200) {
            if ('error_code' in response) {
              if (response.error_code === 0) {
                resolve(response.result);
              } else {
                reject({message: response.reason, status: response.error_code});
              }
            } else {
              reject({message: body});
            }
          } else {
            reject({message: 'reason' in response ? response.reason : body, status});
          }
        }, (body) => {
          reject({message: body});
        });
    });
  }

  parseResult(result) {
    const ret = {};
    for (const resultKey in API_RETURN_FIELD) {
      if (!API_RETURN_FIELD.hasOwnProperty(resultKey) ||
        !(resultKey in result && result[resultKey] !== null)) {
        continue;
      }

      switch (resultKey) {
        case 'type':
          ret[resultKey] = `${result[resultKey] === 1 ? '人' : '公司'}`;
          break;
        case 'fromTime':
          ret[resultKey] = moment.utc(result[resultKey]).format();
          break;
        case 'base':
          for (let i = 0; i < QichachaProvince.Result.length; i++) {
            if (result[resultKey].toUpperCase() === QichachaProvince.Result[i].Code) {
              ret[resultKey] = QichachaProvince.Result[i].ProvinceName;
              break;
            }
          }
          if (!(resultKey in ret)) {
            ret[resultKey] = `${result[resultKey]}`;
          }
          break;
        default:
          ret[resultKey] = `${result[resultKey]}`;
      }
    }
    return ret;
  }
}
